import os
import sys

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from config import *
import datetime
from aws_model.aws_s3 import Operation_aws_s3


def delete_data(bucket, table_name, date, month=True):
    # 删除时间分区
    date = datetime.datetime.strptime(date, '%Y-%m-%d')
    if month:
        last_month = (addmonth(date, -1)).strftime('%Y-%m-%d')
        date = '-'.join(last_month.split('-')[:2])
    else:
        date = (date - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
    if bucket == result_bucket:
        date_col = "time"
    else:
        date_col = "p_date"
    path = f'fridge/{table_name}/{date_col}={date}/'
    delete(bucket, path)


def delete(bucket, path):
    aws_s3 = Operation_aws_s3()
    file_list = aws_s3.list_object(bucket, path)
    if file_list:
        for file in file_list:
            if file:
                filepath = file.get('path')
                aws_s3.empty_object(bucket, filepath)


def addmonth(date, interval):
    y = date.year
    m = date.month + interval
    d = date.day
    while m > 12 or m < 1:
        if m > 12:
            m = m - 12
            y += 1
        elif m < 1:
            m = 12 + m
            y -= 1
    return datetime.datetime(year=y, month=m, day=d)
